package com.sunni.web;

import com.sunni.service.UserServcie;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        ServletContext context = req.getServletContext();
        /*原始写法 : 直接从ServletContext中获取，每次还需要记住spring容器的在作用域里的名字叫app*/
        //ApplicationContext app = (ApplicationContext) context.getAttribute("app");

        /*自定义的*/
        // 优化: 使用工具类获取spring容器 （告诉工具类ServletContext作用域，工具类直接返给你spring容器 ，从这个ServletContext作用域中）
        // ApplicationContext app = GetApplicationContextUtil.getApplicationContext(context);

        /*使用spring官方的*/
        // 优化: 使用工具类获取spring容器
        ApplicationContext app = WebApplicationContextUtils.getWebApplicationContext(context);
        // WebApplicationContext 是 ApplicationContext的子类

        UserServcie userServcie = app.getBean(UserServcie.class);
        userServcie.save();
    }
}
